<template>
  <div class="admin-downloads">
    <div class="page-header">
      <h2>下载管理</h2>
    </div>

    <el-tabs v-model="activeTab" type="card">
      <!-- 下载文件管理 -->
      <el-tab-pane label="下载文件管理" name="files">
        <div class="tab-content">
          <div class="header-actions">
            <el-button 
              v-if="hasPermission('download_add')"
              type="primary" 
              @click="showAddDialog = true"
            >
              添加下载
            </el-button>
          </div>
          
          <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索文件名/描述"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.category" placeholder="文件分类" clearable @change="handleSearch">
            <el-option label="展会资料" value="exhibition" />
            <el-option label="技术文档" value="technical" />
            <el-option label="宣传材料" value="promotion" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.status" placeholder="状态" clearable @change="handleSearch">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 下载列表 -->
    <el-table :data="downloadsList" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="fileName" width="220" label="文件名" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="category" label="分类">
        <template #default="scope">
          {{ getCategoryText(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="fileSize" label="文件大小" />
      <el-table-column prop="downloadCount" label="下载次数" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
            {{ scope.row.status === 'active' ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" width="240" label="上传时间" />
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <div class="action-buttons">
            
            <el-button 
              v-if="hasPermission('download_edit')"
              size="small" 
              type="primary" 
              @click="editDownload(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="hasPermission('download_delete')"
              size="small" 
              type="danger" 
              @click="deleteDownload(scope.row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
        </div>
      </el-tab-pane>
    
    <!-- 添加/编辑下载对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingDownload ? '编辑下载' : '添加下载'"
      width="600px"
    >
      <el-form :model="downloadForm" :rules="downloadRules" ref="downloadFormRef" label-width="100px">
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="downloadForm.fileName" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="downloadForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="downloadForm.category" placeholder="选择分类">
                <el-option label="展会资料" value="exhibition" />
                <el-option label="技术文档" value="technical" />
                <el-option label="宣传材料" value="promotion" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件大小" prop="fileSize">
              <el-input v-model="downloadForm.fileSize" placeholder="由上传自动生成" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
                 <el-form-item label="文件上传" prop="filePath">
           <div class="file-upload-container">
             <el-upload
               class="file-uploader"
               :action="uploadAction"
               :headers="uploadHeaders"
               :data="{ type: 'download' }"
               :show-file-list="false"
               :on-success="handleUploadSuccess"
               :on-error="handleUploadError"
               :before-upload="beforeUpload"
               accept="*/*"
             >
               <el-button type="primary" v-if="!downloadForm.filePath">
                 <el-icon><Upload /></el-icon>
                 选择文件
               </el-button>
               <div v-else class="uploaded-file">
                 <el-icon><Document /></el-icon>
                 <span>{{ downloadForm.fileName || '已上传文件' }}</span>
                 <el-button type="text" @click="removeFile">移除</el-button>
               </div>
             </el-upload>
           </div>
         </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="downloadForm.status">
            <el-radio label="active">正常</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveDownload" :loading="saving">保存</el-button>
      </template>
    </el-dialog>

    <!-- 轮播图管理 -->
    <el-tab-pane label="轮播图管理" name="carousel">
      <div class="tab-content">
        <CarouselManager 
          title="下载中心轮播图管理" 
          module-type="downloads"
        />
      </div>
    </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { downloadApi } from '@/api/admin'
import CarouselManager from '@/components/admin/CarouselManager.vue'
import config from '@/config'
import { Upload, Document } from '@element-plus/icons-vue'

export default {
  name: 'AdminDownloads',
  components: {
    Upload,
    Document,
    CarouselManager
  },
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const showAddDialog = ref(false)
    const editingDownload = ref(null)
    const activeTab = ref('files')
    
    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      category: '',
      status: ''
    })
    
    // 下载表单
    const downloadForm = reactive({
      fileName: '',
      description: '',
      category: '',
      fileSize: '',
      filePath: '',
      status: 'active'
    })
    
    // 表单验证规则
    const downloadRules = {
      fileName: [
        { required: true, message: '请输入文件名', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入描述', trigger: 'blur' }
      ],
      category: [
        { required: true, message: '请选择分类', trigger: 'change' }
      ],
      filePath: [
        { required: true, message: '请上传文件或输入文件路径', trigger: 'blur' }
      ]
    }
    
    // 分页
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })
    
         // 下载数据列表
     const downloadsList = ref([])
     
     // 文件上传相关
     const apiConfig = config.getApiConfig()
     const uploadAction = ref(`${apiConfig.baseURL}/api/upload/file`)
     const uploadHeaders = ref({
       'token': localStorage.getItem('adminToken') || ''
     })

         // 权限检查 - 开发阶段暂时开放所有权限
     const hasPermission = (permission) => {
       // 开发阶段：暂时返回 true，确保所有按钮都能显示
       console.log(`权限检查: ${permission} - 开发阶段暂时开放`)
       return true
       
       // 生产环境的权限检查逻辑（暂时注释）
       /*
       // 尝试多个可能的存储位置
       let userInfo = null
       const possibleKeys = ['adminUser', 'userInfo', 'user', 'adminInfo']
       
       for (const key of possibleKeys) {
         const stored = localStorage.getItem(key)
         if (stored) {
           try {
             userInfo = JSON.parse(stored)
             if (userInfo && (userInfo.permissions || userInfo.roles)) {
               break
             }
           } catch (e) {
             console.warn(`Failed to parse ${key}:`, e)
           }
         }
       }
       
       // 如果没有找到用户信息，临时返回 true 用于开发测试
       if (!userInfo) {
         console.warn('No user info found, temporarily allowing all permissions for development')
         return true
       }
       
       // 检查权限
       if (userInfo.permissions?.includes('all') || userInfo.roles?.includes('admin')) {
         return true
       }
       
       // 支持多种权限格式
       const permissions = userInfo.permissions || userInfo.permission || []
       const roles = userInfo.roles || userInfo.role || []
       
       return permissions.includes(permission) || roles.includes(permission) || false
       */
     }
    
    // 获取分类文本
    const getCategoryText = (rowOrValue) => {
      const value = typeof rowOrValue === 'object' ? (rowOrValue.category || rowOrValue.type || rowOrValue.cat) : rowOrValue
      const texts = {
        exhibition: '展会资料',
        technical: '技术文档',
        promotion: '宣传材料',
        other: '其他',
        material: '资料',
        document: '文档',
        guide: '指南',
        form: '表单'
      }
      // 兜底：若有后端返回中文，直接展示；若为空则显示 "-"
      if (!value) return '-'
      return texts[value] || value
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      loadDownloads()
    }
    
    // 重置搜索
    const resetSearch = () => {
      searchForm.keyword = ''
      searchForm.category = ''
      searchForm.status = ''
      pagination.current = 1
      loadDownloads()
    }
    
    // 加载下载数据
    const loadDownloads = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.current,
          size: pagination.size,
        }
        // 关键字兼容多种后端入参
        if (searchForm.keyword) {
          params.keyword = searchForm.keyword
          params.q = searchForm.keyword
          params.query = searchForm.keyword
          params.fileName = searchForm.keyword
          params.title = searchForm.keyword
          params.description = searchForm.keyword
        }
        // 分类兼容多种后端入参
        if (searchForm.category) {
          params.category = searchForm.category
          params.type = searchForm.category
          params.cat = searchForm.category
        }
        // 状态兼容多种后端入参
        if (searchForm.status) {
          params.status = searchForm.status
          params.state = searchForm.status
        }

        const response = await downloadApi.getDownloadPage(params)
        if (response.code === '200') {
          let records = response.data.records || []
          // 前端兜底过滤：文件名/标题/描述 模糊匹配
          const kw = (searchForm.keyword || '').trim().toLowerCase()
          if (kw) {
            records = records.filter(it => {
              const fileName = (it.fileName || it.filename || it.file_name || it.title || '').toLowerCase()
              const desc = (it.description || '').toLowerCase()
              return fileName.includes(kw) || desc.includes(kw)
            })
          }
          downloadsList.value = records
          // 若前端过滤生效，重置 total 为过滤后的数量
          pagination.total = kw ? records.length : (response.data.total || 0)
        }
      } catch (error) {
        console.error('加载下载数据失败:', error)
        ElMessage.error('加载下载数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 查看功能已移除
    
    // 编辑下载
    const editDownload = (download) => {
      editingDownload.value = download
      Object.assign(downloadForm, {
        fileName: download.fileName || download.title, // 兼容title字段
        description: download.description,
        category: download.category,
        fileSize: download.fileSize,
        filePath: download.filePath,
        status: download.status
      })
      showAddDialog.value = true
    }
    
    // 删除下载
    const deleteDownload = async (download) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除下载文件 "${download.fileName}" 吗？此操作不可恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 调用删除API
        await downloadApi.deleteDownload(download.id)
        ElMessage.success('删除成功')
        await loadDownloads() // 重新加载数据
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除下载失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }
    
         // 处理文件上传成功
    const handleUploadSuccess = (response) => {
      if (response && (response.code === '200' || response.code === 200)) {
        downloadForm.filePath = response.data.url
        downloadForm.fileName = response.data.name || response.data.fileName || '上传的文件'
        // 将文件大小转换为数字类型
        downloadForm.fileSize = response.data.size ? parseInt(response.data.size) : 0
        ElMessage.success('文件上传成功!')
      } else {
        const msg = response?.msg || response?.message || '文件上传失败!'
        ElMessage.error(msg)
      }
    }
    
    // 处理文件上传失败（网络或后端500等）
    const handleUploadError = (err) => {
      let msg = '文件上传失败!'
      try {
        const data = err?.response?.data
        if (data && (data.msg || data.message)) {
          msg = data.msg || data.message
        } else if (typeof err?.message === 'string' && err.message) {
          msg = err.message
        }
      } catch (_) {}
      ElMessage.error(msg)
    }
    
    // 上传前检查
    const beforeUpload = (file) => {
      const isLt100M = file.size / 1024 / 1024 < 100
      
      if (!isLt100M) {
        ElMessage.error('文件大小不能超过 100MB!')
        return false
      }
      return true
    }
    
    // 移除文件
    const removeFile = () => {
      downloadForm.filePath = ''
      downloadForm.fileName = ''
      downloadForm.fileSize = ''
    }
     
    // 保存下载
    const saveDownload = async () => {
      saving.value = true
      
      try {
        const formData = {
          title: downloadForm.fileName, // 使用fileName作为title
          fileName: downloadForm.fileName,
          description: downloadForm.description,
          category: downloadForm.category,
          // 由后端/上传结果维护，不允许手填
          fileSize: downloadForm.fileSize ? parseInt(downloadForm.fileSize) : 0,
          filePath: downloadForm.filePath,
          status: downloadForm.status
        }
        if (!formData.filePath) {
          ElMessage.error('请先上传文件')
          saving.value = false
          return
        }
        
        if (editingDownload.value) {
          // 编辑下载
          formData.id = editingDownload.value.id
          await downloadApi.updateDownload(formData)
          ElMessage.success('下载更新成功')
        } else {
          // 添加下载
          await downloadApi.addDownload(formData)
          ElMessage.success('下载添加成功')
        }
        
        showAddDialog.value = false
        editingDownload.value = null
        Object.assign(downloadForm, {
          fileName: '',
          description: '',
          category: '',
          fileSize: '',
          filePath: '',
          status: 'active'
        })
        
        await loadDownloads() // 重新加载数据
      } catch (error) {
        console.error('保存下载失败:', error)
        ElMessage.error('保存失败: ' + (error.message || '未知错误'))
      } finally {
        saving.value = false
      }
    }
    
    // 导出功能已下线
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      loadDownloads()
    }
    
    const handleCurrentChange = (current) => {
      pagination.current = current
      loadDownloads()
    }
    
    onMounted(() => {
      loadDownloads()
    })
    
    return {
      loading,
      saving,
      showAddDialog,
      editingDownload,
      activeTab,
      searchForm,
      downloadForm,
      downloadRules,
      pagination,
      downloadsList,
      hasPermission,
      getCategoryText,
             handleSearch,
       resetSearch,
       editDownload,
       deleteDownload,
       saveDownload,
       handleSizeChange,
       handleCurrentChange,
       handleUploadSuccess,
       handleUploadError,
       beforeUpload,
       removeFile,
       uploadAction,
       uploadHeaders
    }
  }
}
</script>

<style scoped>
.admin-downloads {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  margin: 0;
  flex-shrink: 0;
}

/* 文件上传样式 */
.file-upload-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.file-uploader {
  display: inline-block;
}

.uploaded-file {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.uploaded-file .el-icon {
  color: #409eff;
}

.uploaded-file span {
  flex: 1;
  color: #606266;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 3px;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style> 